<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="800px"
    append-to-body
    :before-close="close"
  >
    <el-form :model="form" ref="form" label-width="120px" :rules="rules">
      <el-form-item label="银行卡账户" prop="settleType" required>
        <el-radio-group v-model="form.settleType">
          <el-radio label="1" v-if="data.proprietorType == 2">对公账户</el-radio>
          <el-radio label="2">对私法人</el-radio>
        </el-radio-group>
      </el-form-item>
      <!--      <el-form-item label="结算方式" prop="settlementMethod" required>-->
      <!--        <el-select v-model="form.settlementMethod" disabled>-->
      <!--          <el-option label="自动结算" value="1"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="银行卡号" prop="cardNo">
        <el-input v-model="form.cardNo" placeholder="请输入银行卡号" maxlength="19"></el-input>
      </el-form-item>
      <el-form-item label="开户行所在地" prop="bankLocation">
        <el-cascader :props="locationProps" v-model="form.bankLocation"></el-cascader>
      </el-form-item>
      <el-form-item label="开户银行" prop="parentBankCode">
        <el-select v-model="bankNumber" style="width: 100%;" :filter-method="filterBank" filterable
                   @change="selectBankChange" @focus="filterBank()"
        >
          <el-option :label="item.bankName" :value="item.bankNumber" v-for="item in bankList" :key="item.id"
          ></el-option>

          <pagination style="text-align: center" v-show="bankTotal > 0" :total="bankTotal"
                      :page.sync="bankQueryParams.pageNum"
                      :limit.sync="bankQueryParams.pageSize"
                      layout="total, prev, pager, next, jumper"
                      :pager-count="5"
                      @pagination="getBankList"
          />

        </el-select>
      </el-form-item>
      <el-form-item label="银行支行" prop="branchBankCode">
        <el-select v-model="branchNumber" style="width: 100%;" filterable :filter-method="filterBranch"
                   @change="selectBranchChange" @focus="filterBranch()"
        >
          <el-option :label="item.branchName" :value="item.branchNumber" v-for="item in bankBranchList" :key="item.id">
          </el-option>
          <pagination style="text-align: center" v-show="bankBranchTotal > 0" :total="bankBranchTotal"
                      :page.sync="branchQueryParams.pageNum"
                      :limit.sync="branchQueryParams.pageSize"
                      layout="total, prev, pager, next, jumper"
                      :pager-count="5"
                      @pagination="getBankBranchList"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="银行卡正面照片" prop="settlePhotoA">
        <image-upload v-model="form.settlePhotoAUrl" :limit="1" @change="settlePhotoAChange" :fileSize="2"/>
      </el-form-item>
      <el-form-item label="银行卡背面照片" prop="settlePhotoB">
        <image-upload v-model="form.settlePhotoBUrl" :limit="1" @change="settlePhotoBChange" :fileSize="2"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { debounce } from '@/utils'
import { settleBankCardProprietor } from '@/api/contract/proprietor'
import { listArea, listBank, listBankBranch, listCity, listProvince, uploadAuthImage } from '@/api/account/yima'

export default {
  name: 'settlement-bankcard',
  components: {},
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      default: '代理服务信息'
    },
    data: {}
  },
  data() {
    return {
      loading: false,
      form: {
        settleType: '1', //1：对公，2：对私法人
        cardNo: '', //卡号
        parentBankName: '', //结算开户银行名称
        parentBankCode: '', //结算开户银行code
        province: '', //开户行所在省
        city: '', //开户行所在市
        settlePhotoA: '', //结算卡正面
        settlePhotoB: '', //结算卡背面
        branchBankName: '', //开户支行名称
        branchBankCode: '', //开户支行code
        bankLocation: '' //开户行所在地
      },
      //银行筛选条件
      bankQueryParams: {
        pageNum: 1,
        pageSize: 20,
        bankName: ''
      },
      //银行
      bankNumber: '',
      bankList: [],
      bankTotal: 0,

      //支行筛选条件
      branchQueryParams: {
        pageNum: 1,
        pageSize: 20,
        branchName: '',
        bankNumber: ''
      },
      //支行
      branchNumber: '',
      bankBranchList: [],
      bankBranchTotal: 0,
      //配置省市区选择器
      locationProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          setTimeout(() => {
            const data = []
            if (level === 0) {
              listProvince().then(res => {
                let list = res.data.map(item => {
                  return { value: item.provinceCode, label: item.provinceName }
                })
                data.push(...list)
                resolve(data)
              })
            } else if (level === 1) {
              listCity(node.value).then(res => {
                let list = res.data.map(item => {
                  return { value: item.cityCode, label: item.cityName }
                })
                data.push(...list)
                resolve(data)
              })
            } else if (level === 2) {
              console.log('node',node)
              let path = node.path
              listArea(path[0], path[1]).then(res => {
                let list = res.data.map(item => {
                  return { value: item.areaCode, label: item.areaName,leaf:true }
                })
                data.push(...list)
                resolve(data)
              })
            }
            resolve(data)
          })
        }
      },
      rules: {
        cardNo: [
          { required: true, message: '请输入银行卡号', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              // 长度为19位且为数字
              if (/^[1-9]\d{9,29}$/.test(value)) {
                callback()
              } else {
                callback(new Error('银行卡号格式不正确'))
              }
            }
          }
        ],
        parentBankCode: [
          { required: true, message: '请选择开户银行', trigger: 'change' }
        ],
        branchBankCode: [
          { required: true, message: '请选择开户支行', trigger: 'change' }
        ],
        settlePhotoA: [
          { required: true, message: '请上传银行卡正面照片', trigger: 'change' }
        ],
        settlePhotoB: [
          { required: true, message: '请上传银行卡背面照片', trigger: 'change' }
        ],
        bankLocation: [
          { required: true, message: '请输入开户行所在地', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    init() {
      this.reset()
    },
    reset() {
      this.form = {
        settleType: '2', //1：对公，2：对私法人
        cardNo: '', //卡号
        parentBankName: '', //结算开户银行名称
        parentBankCode: '', //结算开户银行code
        province: '', //开户行所在省
        city: '', //开户行所在市
        area: '', //开户行所在区
        settlePhotoA: '', //结算卡正面
        settlePhotoAUrl: '', //结算卡正面url
        settlePhotoB: '', //结算卡背面
        settlePhotoBUrl: '', //结算卡背面url
        branchBankName: '', //开户支行名称
        branchBankCode: '', //开户支行code
        bankLocation: '' //开户行所在地
      }
      this.bankNumber = ''
      this.branchNumber = ''
      this.resetForm('form')

    },
    //获取银行列表
    getBankList() {
      listBank(this.bankQueryParams).then(res => {
        this.bankList = res.rows
        this.bankTotal = res.total
      })
    },
    //获取支行列表
    getBankBranchList() {
      listBankBranch(this.branchQueryParams).then(res => {
        this.bankBranchList = res.rows
        this.bankBranchTotal = res.total
      })
    },
    //选择银行
    filterBank: debounce(function(item) {
      console.log('item', item)
      this.bankQueryParams.bankName = item
      this.bankQueryParams.pageNum = 1
      this.getBankList()
    }, 500, true),
    //选择银行后，获取支行列表
    selectBankChange(val) {
      let bank = this.bankList.find(item => item.bankNumber === val)
      this.form.parentBankName = bank.bankName
      this.form.parentBankCode = bank.bankNumber

      this.branchQueryParams.bankNumber = bank.bankNumber //设置支行对应的银行

      //清空支行筛选条件
      this.branchNumber = ''
      this.branchQueryParams.branchName = ''
      this.branchQueryParams.pageNum = 1
      this.bankBranchList = []
      this.bankBranchTotal = 0
    },

    //筛选支行数据回调
    filterBranch: debounce(function(query) {
      if(!this.branchQueryParams.bankNumber) return
      this.branchQueryParams.branchName = query
      this.getBankBranchList()
    }, 500, true),
    //选择支行后
    selectBranchChange(val) {
      let branch = this.bankBranchList.find(item => item.branchNumber == val)
      this.form.branchBankName = branch.branchName
      this.form.branchBankCode = branch.branchNumber
    },
    // 上传银行卡正面照片
    settlePhotoAChange(fileList,file) {
      if(!file.raw) return
      this.loading = true
      let form = new FormData()
      form.append('file', file.raw)
      uploadAuthImage(form,13).then(res => {
        this.form.settlePhotoA = res.data
        this.loading = false
      }).catch(err => {
        console.log(err)
        this.form.settlePhotoAUrl = ''
        this.loading = false
      })
    },
    // 上传银行卡背面照片
    settlePhotoBChange(fileList,file) {
      if(!file.raw) return
      this.loading = true
      let form = new FormData()
      form.append('file', file.raw)
      uploadAuthImage(form,14).then(res => {
        this.form.settlePhotoB = res.data
        this.loading = false
      }).catch(err => {
        console.log(err)
        this.form.settlePhotoBUrl = ''
        this.loading = false
      })
    },
    // 提交表单
    submit: debounce(function() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.province = this.form.bankLocation[0]
          this.form.city = this.form.bankLocation[1]
          this.form.area = this.form.bankLocation[2]
          settleBankCardProprietor(this.form,this.data.proprietorId).then(res => {
            this.$message.success(res.msg)
            this.visible = false
            this.$emit('success')
          }).catch(err => {
            console.log(err)
          })
        } else {
          return false
        }
      })
    }, 500, true),
    close() {
      this.visible = false
    }
  }
}
</script>


<style scoped lang="scss">
::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  height: 100%;

  .qrcode-container__qrcode {
    height: 200px;
    height: 200px;
  }
}

</style>
